#include "linemessage.h"
#include<QHBoxLayout>
#include<QVBoxLayout>


LineMessage::LineMessage(LineMessageData lmDate, MessageUser msgUser, QWidget *parent)
{
    QHBoxLayout*hly=new QHBoxLayout(this);//存所有内容

    //头像区域
    lbhead=new QLabel(this);
    lbhead->setPixmap(QPixmap(lmDate.headimage));
    lbhead->setAlignment(Qt::AlignRight);
    lbhead->setMinimumWidth(40);
    lbhead->setMaximumWidth(40);

    //内容和标签区域
    msg=new QWidget(this);
    title=new QWidget(this);
    QVBoxLayout* msgLayout = new QVBoxLayout(msg);
    QHBoxLayout* titleLayout = new QHBoxLayout(title);

    sendtime=new QLabel(title);
    usermessage=new QLabel(msg);
    usermessage->setText(lmDate.message);
    usermessage->setMaximumWidth(570);
    usermessage->setMinimumWidth(570);
    usermessage->setWordWrap(true); // 启用自动换行

    titleLayout->addWidget(sendtime);
    msgLayout->addWidget(title);
    msgLayout->addWidget(usermessage);

    // ============ 关键修复：设置布局对齐方式 ============
    msgLayout->setAlignment(Qt::AlignTop);        // 确保内容顶部对齐
    msgLayout->setContentsMargins(0, 0, 0, 0);    // 去掉内边距
    msgLayout->setSpacing(2);                     // 设置标题和消息间距
    titleLayout->setContentsMargins(0, 0, 0, 0);  // 去掉标题内边距
    // ==================================================

    if(msgUser==MessageUser_self)
    {
        QString txtTitle=QString("%1 %2").arg(QString("2021/04/07 00:00:00")).arg(lmDate.name);
        sendtime->setText(txtTitle);
        sendtime->setMinimumWidth(570);
        sendtime->setMaximumWidth(570);
        sendtime->setAlignment(Qt::AlignRight);
        usermessage->setAlignment(Qt::AlignRight);
        lbhead->setAlignment(Qt::AlignRight);
        hly->addWidget(msg);
        hly->addWidget(lbhead);
    }
    else
    {
        QString txtTitle=QString("%2 %1").arg(QString("2021/04/07 00:00:00")).arg(lmDate.name);
        sendtime->setText(txtTitle);
        sendtime->setMinimumWidth(570);
        sendtime->setMaximumWidth(570);
        sendtime->setAlignment(Qt::AlignLeft);
        usermessage->setAlignment(Qt::AlignLeft);
        lbhead->setAlignment(Qt::AlignLeft);
        hly->addWidget(lbhead);
        hly->addWidget(msg);
    }

    // 设置主布局
    hly->setContentsMargins(10, 5, 10, 5); // 设置边距
    hly->setSpacing(10);                    // 设置间距

    // ============ 添加动态高度计算 ============
    QFontMetrics fm(usermessage->font());
    QRect textRect = fm.boundingRect(0, 0, 570, 0, Qt::TextWordWrap, lmDate.message);
    int textHeight = textRect.height();
    int titleHeight = fm.height(); // 标题高度

    // 总高度 = 标题高度 + 消息高度 + 布局间距 + 边距
    int totalHeight = titleHeight + textHeight + 10 + 10;

    // 确保最小高度
    totalHeight = qMax(totalHeight, 60);

    this->setMinimumHeight(totalHeight);
    this->setMaximumHeight(totalHeight);
    // =========================================

    this->setMinimumWidth(640);
}

LineMessage::~LineMessage()
{

}

